﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.SportBusiness.CompetitionGroupingInfo;
using SportsPlatform.Dto.SportBusiness.CompetitionRuleInfo;
using SportsPlatform.Enums;
using SportsPlatform.Global;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.SportBusiness.CompetitionGroupingInfo;
using SportsPlatform.Query.SportBusiness.CompetitionRuleInfo;
using SportsPlatform.SportBusiness.ISportBusiness;
using SportsPlatform.SqlExecuter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 比赛分组
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class CompetitionGroupingInfoService : SportsPlatformAppServiceBase, ICompetitionGroupingInfoService
    {
        private readonly IRepository<CompetitionGroupingInfo, Guid> _competitionGroupingInfo;
        private readonly IRepository<CompetitionProject, Guid> _projectRepository;
        private readonly IRepository<EventsSession, Guid> _eveRepository;
        private readonly ISqlExecuterRepository _sqlExecuterRepository;
        private readonly IRepository<Employee, Guid> _employeeRepository;
        private readonly IRepository<UserInfo, Guid> _userinfoRepository;
        private readonly IRepository<GroupingEmployeeInfo, Guid> _groupemployeeRepository;
        private readonly IRepository<RegistrationInfo, Guid> _regRepository;
        private readonly IRepository<CompeteTeam, Guid> _comTeamRepository;
        private readonly IRepository<CompeteTeamEmployee, Guid> _comTeamEmpRepository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="competitionGroupingInfo"></param>
        /// <param name="eveRepository"></param>
        /// <param name="sqlExecuterRepository"></param>
        /// <param name="employeeRepository"></param>
        /// <param name="groupemployeeRepository"></param>
        /// <param name="regRepository"></param>
        /// <param name="projectRepository"></param>
        /// <param name="comTeamRepository"></param>
        /// <param name="comTeamEmpRepository"></param>
        /// <param name="userinfoRepository"></param>
        /// <param name="context"></param>
        public CompetitionGroupingInfoService(IRepository<CompetitionGroupingInfo, Guid> competitionGroupingInfo, 
            IRepository<EventsSession, Guid> eveRepository,
            ISqlExecuterRepository sqlExecuterRepository,
            IRepository<Employee, Guid> employeeRepository, 
            IRepository<GroupingEmployeeInfo, Guid> groupemployeeRepository,
            IRepository<RegistrationInfo, Guid> regRepository,
            IRepository<CompetitionProject, Guid> projectRepository,
            IRepository<CompeteTeam, Guid> comTeamRepository,
            IRepository<CompeteTeamEmployee, Guid> comTeamEmpRepository,
            IRepository<UserInfo, Guid> userinfoRepository, 
            IHttpContextAccessor context) : base(context)
        {
            _competitionGroupingInfo = competitionGroupingInfo;
            _sqlExecuterRepository = sqlExecuterRepository;
            _employeeRepository = employeeRepository;
            _eveRepository = eveRepository;
            _projectRepository = projectRepository;
            _comTeamRepository = comTeamRepository;
            _userinfoRepository = userinfoRepository;
            _groupemployeeRepository = groupemployeeRepository;
            _regRepository = regRepository;
            _comTeamEmpRepository = comTeamEmpRepository;
        }

        /// <summary>
        /// 新增比赛项目分组信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddCompetitionGroupingInfo(List<AddGroupInfoListsQuery> query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                if (query.Count > 0)
                {
                    var eventSessionId = Guid.Empty;
                    //如果分组信息中未传场次ID，则在新增分组信息的时候先添加一个场次信息
                    if (query.FirstOrDefault().EventsSessionId == Guid.Empty || query.FirstOrDefault().EventsSessionId == null)
                    {
                        var eventsession = new EventsSession();
                        eventsession.Id = Guid.NewGuid();
                        eventsession.CreateUserId = token.Id;
                        eventsession.CreateTime = DateTime.Now;
                        eventsession.IsDeleted = false;
                        eventsession.MatchType = "第一场";
                        eventsession.Race = 1;
                        eventsession.CompetitionProjectId = query.FirstOrDefault().CompetitionProjectId;
                        eventSessionId = await _eveRepository.InsertAndGetIdAsync(eventsession);
                    }
                    else
                    {
                        eventSessionId = (Guid)query.FirstOrDefault().EventsSessionId;

                        //判断当前比赛项目的场次ID是否有分组信息，如果有，则需要删除之前的分组信息，重新保存新的分组信息
                        var group = await _competitionGroupingInfo.GetAllListAsync(a => a.EventsSessionId == eventSessionId && a.IsDeleted == false);
                        if (group.Count > 0)
                        {
                            //删除分组信息
                            var sqlgroup = "UPDATE T_B_CompetitionGroupingInfo SET IsDeleted=1,DeleteTime='" + DateTime.Now + "',DeleteUserId='" + token.Id + "' where EventsSessionId='" + eventSessionId + "'";
                            _sqlExecuterRepository.Execute(sqlgroup, null);

                            //删除参赛团队人员信息
                            var sqlteamcom = "UPDATE T_B_CompeteTeamEmployee SET IsDeleted=1 where EventsSessionId='" + eventSessionId + "'";
                            _sqlExecuterRepository.Execute(sqlteamcom, null);

                            foreach (var item in group)
                            {
                                //删除分组用户信息
                                var sqlgroupemp = "UPDATE T_B_GroupingEmployeeInfo SET IsDeleted=1,DeleteTime='" + DateTime.Now + "',DeleteUserId='" + token.Id + "' where CompetitionGroupingId='" + item.Id + "'";
                                _sqlExecuterRepository.Execute(sqlgroupemp, null);
                            }
                        }
                    }
                    var comprojectinfo = await _projectRepository.FirstOrDefaultAsync(query.FirstOrDefault().CompetitionProjectId);
                    //循环保存分组数据信息
                    foreach (var item in query)
                    {
                        //保存分组信息
                        var groupinfo = new CompetitionGroupingInfo();
                        groupinfo.CompetitionProjectId = item.CompetitionProjectId;
                        groupinfo.EventsSessionId = eventSessionId;
                        groupinfo.Name = item.Name;
                        groupinfo.CreateUserId = token.Id;
                        groupinfo.CreateTime = DateTime.Now;
                        groupinfo.IsDeleted = false;
                        Guid groupid=await _competitionGroupingInfo.InsertAndGetIdAsync(groupinfo);
                        foreach (var g in item.Grouplist)
                        {
                            
                                //保存组员信息
                                var groupempinfo = new GroupingEmployeeInfo();
                                groupempinfo.CompetitionProjectId = item.CompetitionProjectId;
                                groupempinfo.CompetitionGroupingId = groupid;
                                groupempinfo.CompeteTeamId = g.CompeteTeamId;
                                groupempinfo.EmployeeId = g.EmployeeId;
                                groupempinfo.Sensor = g.Sensor;
                                groupempinfo.NoLocation = g.NoLocation;
                                groupempinfo.CreateUserId = token.Id;
                                groupempinfo.CreateTime = DateTime.Now;
                                groupempinfo.IsDeleted = false;
                                await _groupemployeeRepository.InsertAsync(groupempinfo);
                            if (comprojectinfo.GameType == (int)CompetitionProjectTypeEnum.团队接力赛)
                            {
                                foreach (var emp in g.CompeteTeamInfos)
                                {
                                    var comteamempinfo = new CompeteTeamEmployee();
                                    comteamempinfo.CompeteTeamId = (Guid)g.CompeteTeamId;
                                    comteamempinfo.EventsSessionId = eventSessionId;
                                    comteamempinfo.EmployeeId = emp.EmployeeId;
                                    comteamempinfo.Sensor = emp.Sensor;
                                    comteamempinfo.IsDeleted = false;
                                    await _comTeamEmpRepository.InsertAsync(comteamempinfo);
                                }
                            }
                        }
                    }
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Message = "保存成功";
                }

            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 分组信息同步
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> GroupingInfoSynchronization(List<GroupingInfoSynchronizationQuery> query)
        {
            BaseResultDto resultDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                //同步之前删除之前项目Id的分组
                var querygrouplist = query
                    .GroupBy(group => new { group.CompetitionProjectId })
                    .Select(group => group.FirstOrDefault())
                    .ToList();
                querygrouplist.ForEach(item =>
                {
                    //删除分组信息
                    var sql = "UPDATE T_B_CompetitionGroupingInfo SET IsDeleted=1,DeleteTime='" + DateTime.Now + "',DeleteUserId='" + token.Id + "' where CompetitionProjectId='" + item.CompetitionProjectId + "'";
                    _sqlExecuterRepository.Execute(sql, null);
                    //删除分组人员信息
                    var sql1 = "UPDATE T_B_GroupingEmployeeInfo SET IsDeleted=1,DeleteTime='" + DateTime.Now + "',DeleteUserId='" + token.Id + "' where CompetitionProjectId='" + item.CompetitionProjectId + "'";
                    _sqlExecuterRepository.Execute(sql1, null);
                    //删除参赛团队人员分组信息
                    var sql2 = $"UPDATE T_B_CompeteTeamEmployee SET IsDeleted=1 where EventsSessionId IN(SELECT EventsSessionId FROM T_B_CompetitionGroupingInfo where  CompetitionProjectId='{item.CompetitionProjectId}')";
                    _sqlExecuterRepository.Execute(sql2, null);
                });
                var projectlist = await _projectRepository.GetAllListAsync();
                var userlist = await _userinfoRepository.GetAllListAsync();
                var eventlist = await _eveRepository.GetAllListAsync();
                var emplist = await _employeeRepository.GetAllListAsync();
                var grouplist = await _competitionGroupingInfo.GetAllListAsync();
                var groupemplist = await _groupemployeeRepository.GetAllListAsync();
                var comteamemplist = await _comTeamEmpRepository.GetAllListAsync();
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Fail;
                foreach (var item in query)
                {
                    #region 数据验证
                    if (projectlist.FirstOrDefault(info => info.Id == item.CompetitionProjectId) == null)
                    {
                        resultDto.Message += $"项目Id:{item.CompetitionProjectId}不存在;";
                        continue;
                    }
                    if (eventlist.FirstOrDefault(info => info.Id == item.EventsSessionId) == null)
                    {
                        resultDto.Message += $"场次Id:{item.EventsSessionId}不存在;";
                        continue;
                    }
                    if (item.CreateUserId != null && userlist.FirstOrDefault(info => info.Id == item.CreateUserId) == null)
                    {
                        resultDto.Message += $"创建用户Id:{item.CreateUserId}不存在;";
                        continue;
                    }
                    #endregion

                    Guid groupid = Guid.Empty;
                    //跟新分组信息
                    //如果id不存在就新建,否则就更新
                    var info = item.Id == null ? null : grouplist.FirstOrDefault(info => info.Id == item.Id);
                    if (info == null)
                    {
                        var groupinfo = ObjectMapper.Map<CompetitionGroupingInfo>(item);
                        groupinfo.Id = item.Id??Guid.NewGuid();
                        if (item.CreateTime == null)
                        {
                            groupinfo.CreateTime = DateTime.Now;
                        }
                        if (item.CreateUserId == null)
                        {
                            groupinfo.CreateUserId = token.Id;
                        }
                        groupid= await _competitionGroupingInfo.InsertAndGetIdAsync(groupinfo);
                    }
                    else
                    {
                        groupid = info.Id;
                        info.CompetitionProjectId = item.CompetitionProjectId;
                        info.EventsSessionId = item.EventsSessionId;
                        info.Name = item.Name;
                        info.CreateTime = item.CreateTime ?? DateTime.Now;
                        info.CreateUserId = item.CreateUserId ?? token.CreateUserId;
                        info.IsDeleted = item.IsDeleted ?? false;
                        info.UpdateTime = null;
                        info.UpdateUserId = null;
                        info.DeleteTime = null;
                        info.DeleteUserId = null;
                        await _competitionGroupingInfo.UpdateAsync(info);
                    }
                    if (groupid == Guid.Empty)
                    {
                        resultDto.Message += $"分组增加错误！;";
                        continue;
                    }
                    //循环更新分组用户信息
                    foreach (var empitem in item.GroupEmployeeList)
                    {
                        if (empitem.EmployeeId!=null && emplist.FirstOrDefault(info => info.Id == empitem.EmployeeId) == null)
                        {
                            resultDto.Message += $"参赛用户Id:{empitem.EmployeeId}不存在;";
                            continue;
                        }
                        var empinfo=empitem.Id==null?null:groupemplist.FirstOrDefault(info => info.Id==empitem.Id);
                        if (empinfo == null)
                        {
                            var emp = ObjectMapper.Map<GroupingEmployeeInfo>(empitem);
                            emp.Id = empitem.Id ?? Guid.NewGuid();
                            emp.CompetitionProjectId=item.CompetitionProjectId;
                            emp.CompetitionGroupingId = groupid;
                            if (empitem.CreateTime == null)
                            {
                                emp.CreateTime = DateTime.Now;
                            }
                            if (empitem.CreateUserId == null)
                            {
                                emp.CreateUserId = token.Id;
                            }
                            await _groupemployeeRepository.InsertAsync(emp);
                        }
                        else {
                            empinfo.CompetitionProjectId = item.CompetitionProjectId;
                            empinfo.CompetitionGroupingId=groupid;
                            empinfo.CompeteTeamId = empitem.CompeteTeamId;
                            empinfo.EmployeeId=empitem.EmployeeId;
                            empinfo.NoLocation=empitem.NoLocation;
                            empinfo.Sensor=empitem.Sensor;
                            empinfo.CreateTime = item.CreateTime ?? DateTime.Now;
                            empinfo.CreateUserId = item.CreateUserId ?? token.CreateUserId;
                            empinfo.IsDeleted = item.IsDeleted ?? false;
                            empinfo.UpdateTime = null;
                            empinfo.UpdateUserId = null;
                            empinfo.DeleteTime = null;
                            empinfo.DeleteUserId = null;
                            await _groupemployeeRepository.UpdateAsync(empinfo);
                        }
                        //如果是团体赛，还要同步参赛团队人员信息
                        if (projectlist.FirstOrDefault(info => info.Id == item.CompetitionProjectId)?.GameType == (int)CompetitionProjectTypeEnum.团队接力赛)
                        {
                            foreach (var teamempitem in empitem.CompeteTeamInfos)
                            {
                                var teamempiteminfos = teamempitem.Id == null ? null : comteamemplist.FirstOrDefault(info => info.Id == teamempitem.Id);
                                if (teamempiteminfos == null)
                                {
                                    CompeteTeamEmployee teamempinfo = new();
                                    teamempinfo.Id = teamempitem.Id ?? Guid.NewGuid();
                                    teamempinfo.CompeteTeamId = (Guid)empitem.CompeteTeamId;
                                    teamempinfo.EventsSessionId = item.EventsSessionId;
                                    teamempinfo.EmployeeId = teamempitem.EmployeeId;
                                    teamempinfo.Sensor = teamempitem.Sensor;
                                    teamempinfo.IsDeleted = false;
                                    await _comTeamEmpRepository.InsertAsync(teamempinfo);
                                }
                                else {
                                    teamempiteminfos.CompeteTeamId = (Guid)empitem.CompeteTeamId;
                                    teamempiteminfos.EventsSessionId = item.EventsSessionId;
                                    teamempiteminfos.EmployeeId = teamempitem.EmployeeId;
                                    teamempiteminfos.Sensor = teamempitem.Sensor;
                                    teamempiteminfos.IsDeleted = false;
                                    await _comTeamEmpRepository.UpdateAsync(teamempiteminfos);
                                }
                            }
                        }
                    }
                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                }
                resultDto.Message = string.IsNullOrEmpty(resultDto.Message) ? "操作成功！" : resultDto.Message;
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 判断当前赛事项目是否存在分组信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<JudgeGroupinfoByEventsIdDto>> JudgeGroupinfoByEventsId(JudgeGroupinfoByEventsIdQuery query)
        {
            var res = new ResultDto<JudgeGroupinfoByEventsIdDto>();
            JudgeGroupinfoByEventsIdDto dto = new JudgeGroupinfoByEventsIdDto();
            var eventsession = await _eveRepository.FirstOrDefaultAsync(a => a.CompetitionProjectId == query.ProjectId && a.IsDeleted == false);
            if (eventsession != null)
            {
                var group = await _competitionGroupingInfo.GetAllListAsync(a => a.EventsSessionId == eventsession.Id && a.IsDeleted == false);
                if (group.Count > 0)
                {
                    res.IsSuccess = true;
                    res.Message = "存在分组信息";
                    res.Code = HttpResultCode.Success;
                    dto.IsHave = true;
                    dto.EventsSessionId = eventsession.Id;
                    res.Data = dto;
                }
                else
                {
                    res.IsSuccess = true;
                    res.Message = "不存在分组信息";
                    res.Code = HttpResultCode.Success;
                    dto.IsHave = false;
                    dto.EventsSessionId = null;
                    res.Data = dto;
                }
            }
            else
            {
                res.IsSuccess = true;
                res.Message = "不存在分组信息";
                res.Code = HttpResultCode.Success;
                dto.IsHave = false;
                dto.EventsSessionId = null;
                res.Data = dto;
            }

            return res;
        }

        /// <summary>
        /// 根据场次ID获取分组列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetGroupInfoListByEventSessionIdDto>> GetGroupInfoListByEventSessionId(GetGroupInfoListByEventSessionIdQuery query)
        {
            var res = new ResultDto<GetGroupInfoListByEventSessionIdDto>();
            try
            {
                //分组信息
                var groupinfolist = new List<GroupInfo>();
                //未分组信息
                var nogrouplist = new List<GroupingInfo>();
                var grouplist = await _competitionGroupingInfo.GetAllListAsync(a => a.EventsSessionId == query.EventSessionId && a.IsDeleted == false);
                var eveinfo = await _eveRepository.GetAsync(query.EventSessionId);
                grouplist = grouplist.OrderBy(a => a.CreateTime).ToList();
                if (grouplist.Count > 0)
                {
                    var reglist = await _regRepository.GetAllListAsync(info => info.CompetitionProjectId == eveinfo.CompetitionProjectId
                    && info.IsDeleted == false && info.RegistrationStatus == (int)RegistrationStatusEnum.报名成功);
                    var employeelist = await _employeeRepository.GetAllListAsync();
                    var groupemplist = await _groupemployeeRepository.GetAllListAsync(info => info.IsDeleted == false);
                    var comprojectlist = await _projectRepository.FirstOrDefaultAsync(eveinfo.CompetitionProjectId);
                    var comteamlist = await _comTeamRepository.GetAllListAsync(info => info.IsDeleted == false && info.CompetitionProjectId == eveinfo.CompetitionProjectId);
                    var comteamemplist = await _comTeamEmpRepository.GetAllListAsync(info => info.IsDeleted == false && info.EventsSessionId == query.EventSessionId);
                    foreach (var groupitem in grouplist)
                    {
                        var dto = new GroupInfo();
                        dto.Id = groupitem.Id;
                        dto.Name = groupitem.Name;
                        dto.EventsSessionId = eveinfo.Id;
                        dto.EventsSessionName = (eveinfo.Race == 1 ? "预赛" : "决赛") + "-" + eveinfo.MatchType;
                        var ginfos = new List<GroupingInfo>();
                        var empinfolist = groupemplist.Where(info => info.CompetitionGroupingId == groupitem.Id).ToList().OrderBy(a => a.NoLocation).ToList();
                        foreach (var item in empinfolist)
                        {
                            var g = new GroupingInfo();
                            g.CompeteTeamId = item.CompeteTeamId;
                            g.EmployeeId = item.EmployeeId;
                            g.NoLocation = item.NoLocation ?? 0;
                            g.Sensor = item.Sensor;
                            if (comprojectlist.GameType==(int)CompetitionProjectTypeEnum.个人赛)
                            {
                                var empinfo = employeelist.FirstOrDefault(info => info.Id == item.EmployeeId);
                                g.EmployeeName = empinfo?.RealName;
                                g.EmployeeIdNo = empinfo?.IDNumber;
                                g.CompeteTeamInfos = new();
                                g.NoCompeteTeamInfos = new();
                                //报名表删除已有信息，最后留下未分组的人
                                reglist?.RemoveAll(info => info.CompeteIdNo == empinfo?.IDNumber);
                            }
                            else
                            {
                                List<CompeteTeamInfoDto> competeTeamInfos = new();
                                List<CompeteTeamInfoDto> nocompeteTeamInfos = new();

                                var comteaminfo = comteamlist.FirstOrDefault(info => info.Id == item.CompeteTeamId);
                                g.CompeteTeamName = comteaminfo?.Name;
                                
                                var teamemplist = comteamemplist?.Where(info => info.CompeteTeamId == item.CompeteTeamId);
                                if (teamemplist != null && teamemplist.Count() > 0)
                                {
                                    foreach (var teamempitem in teamemplist)
                                    {
                                        CompeteTeamInfoDto info = new();
                                        info.EmployeeId = teamempitem.EmployeeId;
                                        info.Sensor = teamempitem.Sensor;
                                        info.EmployeeIdNo = employeelist.FirstOrDefault(info => info.Id == teamempitem.EmployeeId)?.IDNumber;
                                        info.EmployeeName = employeelist.FirstOrDefault(info => info.Id == teamempitem.EmployeeId)?.RealName;
                                        competeTeamInfos.Add(info);
                                        //报名表删除已有信息，最后留下未分组的人
                                        reglist?.RemoveAll(a => a.CompeteTeamId == item.CompeteTeamId && a.CompeteIdNo == info.EmployeeIdNo);
                                    }
                                }
                                //查询是否有未分组的团队人员
                                var nolist = reglist.Where(info => info.CompeteTeamId == item.CompeteTeamId).ToList();
                                if (nolist != null && nolist.Count() > 0)
                                {
                                    foreach (var noitem in nolist)
                                    {
                                        var empinfo = employeelist.FirstOrDefault(info => info.IDNumber == noitem.CompeteIdNo && info.RealName == noitem.CompeteName);
                                        CompeteTeamInfoDto info = new();
                                        info.EmployeeId = empinfo.Id;
                                        info.Sensor = noitem.SensorNumber;
                                        info.EmployeeIdNo = noitem.CompeteIdNo;
                                        info.EmployeeName = noitem.CompeteName;
                                        nocompeteTeamInfos.Add(info);
                                    }
                                    reglist?.RemoveAll(info => info.CompeteTeamId == item.CompeteTeamId);
                                }
                                g.CompeteTeamInfos = competeTeamInfos;
                                g.NoCompeteTeamInfos = nocompeteTeamInfos;
                            }
                            ginfos.Add(g);
                        }
                        dto.Grouplists = ginfos;
                        groupinfolist.Add(dto);
                    }

                    if (reglist != null && reglist.Count > 0)
                    {
                        foreach (var reginfo in reglist)
                        {
                            if (comprojectlist.GameType == (int)CompetitionProjectTypeEnum.个人赛)
                            {
                                var info = new GroupingInfo();
                                info.CompeteTeamId = reginfo.CompeteTeamId;
                                var empinfo = employeelist.FirstOrDefault(info => info.IDNumber == reginfo.CompeteIdNo);
                                info.EmployeeId = empinfo?.Id;
                                info.EmployeeName = empinfo?.RealName;
                                info.EmployeeIdNo = empinfo?.IDNumber;
                                info.NoLocation = 0;
                                info.Sensor = reginfo.SensorNumber;
                                info.CompeteTeamInfos = new();
                                info.NoCompeteTeamInfos = new();
                                nogrouplist.Add(info);
                            }
                            else
                            {
                                var nocomteamlist = reglist.GroupBy(info => new { info.CompeteTeamId, info.CompeteTeamName }).Select(g => new { g.Key.CompeteTeamId, g.Key.CompeteTeamName }).ToList();
                                foreach (var item in nocomteamlist)
                                {
                                    var info = new GroupingInfo();
                                    info.CompeteTeamId = item.CompeteTeamId;
                                    info.CompeteTeamName = item.CompeteTeamName;
                                    var teamreglist = reglist.Where(info => info.CompeteTeamId == item.CompeteTeamId);
                                    List<CompeteTeamInfoDto> groupteamlist = new();
                                    foreach (var teamreg in teamreglist)
                                    {
                                        CompeteTeamInfoDto teamempinfo = new();
                                        var empinfo = employeelist.FirstOrDefault(info => info.IDNumber == teamreg.CompeteIdNo);
                                        teamempinfo.EmployeeId = (Guid)empinfo?.Id;
                                        teamempinfo.Sensor = teamreg.SensorNumber;
                                        teamempinfo.EmployeeIdNo = empinfo?.IDNumber;
                                        teamempinfo.EmployeeName = empinfo?.RealName;
                                        groupteamlist.Add(teamempinfo);
                                    }
                                    info.CompeteTeamInfos = groupteamlist;
                                    info.NoCompeteTeamInfos = new();
                                    nogrouplist.Add(info);
                                }
                            }
                        }
                    }
                    res.IsSuccess = true;
                    res.Message = "查询成功";
                    res.Code = HttpResultCode.Success;
                    res.Data = new() { GroupCompetetionInfos = groupinfolist, Grouplists = nogrouplist };
                }
                else
                {
                    res.IsSuccess = false;
                    res.Message = "未查询到数据";
                    res.Code = HttpResultCode.NotData;
                }
            }
            catch (Exception ex)
            {
                res.IsSuccess = false;
                res.Message = ex.Message;
                res.Code = HttpResultCode.Error;
            }

            return res;
        }

        /// <summary>
        /// 获取第一场分组信息客户端
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetGroupCompeteInfoListDto>> GetGroupCompeteInfoList(GetGroupCompeteInfoListQuery query)
        {
            ResultListDto<GetGroupCompeteInfoListDto> resultListDto = new ResultListDto<GetGroupCompeteInfoListDto>();
            try
            {
                var list = new List<GetGroupCompeteInfoListDto>();
                var eveinfo = (await _eveRepository.GetAllListAsync(info => info.CompetitionProjectId == query.CompetitionProjectId && info.IsDeleted == false)).FirstOrDefault();
                if (eveinfo == null)
                {
                    resultListDto.IsSuccess = false;
                    resultListDto.Message = "未查询到数据";
                    resultListDto.Code = HttpResultCode.NotData;
                    return resultListDto;
                }
                var group = await _competitionGroupingInfo.GetAllListAsync(info => info.EventsSessionId == eveinfo.Id && info.IsDeleted == false);
                group = group.OrderBy(a => a.CreateTime).ToList();
                if (group.Count > 0)
                {
                    var comprojectinfo = await _projectRepository.FirstOrDefaultAsync(eveinfo.CompetitionProjectId);
                    var employeelist = await _employeeRepository.GetAllListAsync();
                    var groupemplist = await _groupemployeeRepository.GetAllListAsync(info => info.IsDeleted == false);
                    var comteamlist = await _comTeamRepository.GetAllListAsync(info => info.IsDeleted == false && info.CompetitionProjectId == eveinfo.CompetitionProjectId);
                    var comteamemplist = await _comTeamEmpRepository.GetAllListAsync(info => info.IsDeleted == false && info.EventsSessionId == eveinfo.Id);
                    foreach (var groupitem in group)
                    {
                        var dto = new GetGroupCompeteInfoListDto();
                        dto.Id = groupitem.Id;
                        dto.Name = groupitem.Name;
                        dto.EventsSessionId = eveinfo.Id;
                        dto.EventsSessionName = (eveinfo.Race == 1 ? "预赛" : "决赛") + "-" + eveinfo.MatchType;
                        var ginfos = new List<GroupEmployee>();
                        var empinfolist = groupemplist.Where(info => info.CompetitionGroupingId == groupitem.Id).ToList().OrderBy(a => a.NoLocation).ToList();
                        foreach (var item in empinfolist)
                        {
                            var g = new GroupEmployee();
                            g.Id = item.Id;
                            g.CompeteTeamId = item.CompeteTeamId;
                            g.EmployeeId = item.EmployeeId;
                            g.NoLocation = item.NoLocation;
                            g.Sensor = item.Sensor;
                            if (comprojectinfo.GameType == (int)CompetitionProjectTypeEnum.个人赛)
                            {
                                var empinfo = employeelist.FirstOrDefault(info => info.Id == item.EmployeeId);
                                g.EmployeeName = empinfo?.RealName;
                                g.EmployeeIdNo = empinfo?.IDNumber;
                            }
                            else
                            {
                                g.CompeteTeamName = comteamlist.FirstOrDefault(info => info.Id == item.CompeteTeamId)?.Name;
                                List<GroupCompeteTeamEmployee> teamemployees = new();
                                var teamemplist = comteamemplist?.Where(info => info.CompeteTeamId == item.CompeteTeamId);
                                foreach (var e in teamemplist)
                                {
                                    GroupCompeteTeamEmployee empdto = new();
                                    empdto.Id = e.Id;
                                    empdto.EmployeeId=e.EmployeeId;
                                    empdto.EmployeeName = employeelist.FirstOrDefault(info => info.Id == e.EmployeeId)?.RealName;
                                    empdto.EmployeeIdNo = employeelist.FirstOrDefault(info => info.Id == e.EmployeeId)?.IDNumber;
                                    empdto.Sensor = e.Sensor;
                                    teamemployees.Add(empdto);
                                }
                                g.CompeteTeamInfos = teamemployees;
                            }
                            ginfos.Add(g);
                        }
                        dto.Grouplists = ginfos;
                        list.Add(dto);
                    }
                    resultListDto.IsSuccess = true;
                    resultListDto.Message = "查询成功";
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Data = list;
                    resultListDto.Count = list.Count;
                }
                else
                {
                    resultListDto.IsSuccess = false;
                    resultListDto.Message = "未查询到数据";
                    resultListDto.Code = HttpResultCode.NotData;
                }
            }
            catch (Exception ex)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Message = ex.Message.ToString();
                resultListDto.Code = HttpResultCode.Error;
            }
            return resultListDto;
        }
        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="Query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<CompetitionGroupingInfoByUserListDto>> GetCompetitionGroupingInfoByUserList(CompetitionGroupingInfoByUserListQuery Query)
        {
            try
            {
                var ruleInfoListDtos = await _competitionGroupingInfo.GetAllListAsync(c => c.IsDeleted == true);
                List<CompetitionGroupingInfoByUserListDto> ListDto = new List<CompetitionGroupingInfoByUserListDto>();
                foreach (var rule in ruleInfoListDtos)
                {
                    CompetitionGroupingInfoByUserListDto dto = new CompetitionGroupingInfoByUserListDto();

                    ListDto.Add(dto);
                }
                return new PagePagingDto<CompetitionGroupingInfoByUserListDto>()
                {
                    IsSuccess = true,
                    Code = (int)HttpResultCode.Success,
                    Message = "查询成功",
                    Data = ListDto,
                    TotalCount = ruleInfoListDtos.Count,
                    TotalPage = 1
                };
            }
            catch (Exception ex)
            {
                return new PagePagingDto<CompetitionGroupingInfoByUserListDto>()
                {
                    IsSuccess = false,
                    Code = (int)HttpResultCode.Error,
                    Message = ex.Message,
                    Data = null,
                    TotalCount = 0,
                    TotalPage = 0
                };
            }
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="Query"></param>
        /// <returns></returns>
        public async Task<ResultDto<List<CompetitionGroupingInfoByUserDetailsDto>>> GetCompetitionGroupingInfoByUserDetails(CompetitionGroupingInfoByUserDetailsQuery Query)
        {
            try
            {
                var ruleInfoListDtos = await _competitionGroupingInfo.GetAllListAsync(c => c.Id == Query.Id && c.IsDeleted == true);
                List<CompetitionGroupingInfoByUserDetailsDto> ListDto = new List<CompetitionGroupingInfoByUserDetailsDto>();
                foreach (var rule in ruleInfoListDtos)
                {
                    CompetitionGroupingInfoByUserDetailsDto dto = new CompetitionGroupingInfoByUserDetailsDto();

                    ListDto.Add(dto);
                }
                return new ResultDto<List<CompetitionGroupingInfoByUserDetailsDto>>()
                {
                    IsSuccess = true,
                    Code = (int)HttpResultCode.Success,
                    Message = "查询成功",
                    Data = ListDto
                };
            }
            catch (Exception ex)
            {
                return new ResultDto<List<CompetitionGroupingInfoByUserDetailsDto>>()
                {
                    IsSuccess = false,
                    Code = (int)HttpResultCode.Error,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        /// <summary>
        /// 比赛成绩
        /// </summary>
        /// <param name="Query"></param>
        /// <returns></returns>
        public async Task<ResultDto<CompetitionGroupingInfoByUserAchievementDto>> GetCompetitionGroupingInfoByUserAchievement(CompetitionGroupingInfoByUserAchievementQuery Query)
        {
            try
            {
                var ruleInfoListDtos = await _competitionGroupingInfo.GetAllListAsync(c => c.Id == Query.Id && c.IsDeleted == true);
                CompetitionGroupingInfoByUserAchievementDto ListDto = new CompetitionGroupingInfoByUserAchievementDto();
                return new ResultDto<CompetitionGroupingInfoByUserAchievementDto>()
                {
                    IsSuccess = true,
                    Code = (int)HttpResultCode.Success,
                    Message = "查询成功",
                    Data = ListDto
                };
            }
            catch (Exception ex)
            {
                return new ResultDto<CompetitionGroupingInfoByUserAchievementDto>()
                {
                    IsSuccess = false,
                    Code = (int)HttpResultCode.Error,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        /// <summary>
        /// 历史成绩
        /// </summary>
        /// <param name="Query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<CompetitionGroupingInfoByUserAchievementListDto>> GetCompetitionGroupingInfoByUserHistoricalAchievement(CompetitionGroupingInfoByUserAchievementListQuery Query)
        {
            try
            {
                var ruleInfoListDtos = await _competitionGroupingInfo.GetAllListAsync(c => c.Id == Query.UserId && c.IsDeleted == true);
                List<CompetitionGroupingInfoByUserAchievementListDto> ListDto = new List<CompetitionGroupingInfoByUserAchievementListDto>();
                return new PagePagingDto<CompetitionGroupingInfoByUserAchievementListDto>()
                {
                    IsSuccess = true,
                    Code = (int)HttpResultCode.Success,
                    Message = "查询成功",
                    Data = ListDto,
                    TotalCount = ruleInfoListDtos.Count,
                    TotalPage = 1
                };
            }
            catch (Exception ex)
            {
                return new PagePagingDto<CompetitionGroupingInfoByUserAchievementListDto>()
                {
                    IsSuccess = false,
                    Code = (int)HttpResultCode.Error,
                    Message = ex.Message,
                    Data = null,
                    TotalCount = 0,
                    TotalPage = 0
                };
            }
        }
    }
}
